var express = require('express');
var router = express.Router();

var Product = require('../schema/ProductsSchema'); //引入对象
var Classify = require('../schema/ClassifiesSchema'); //引入对象


// 获取首页商品列表
router.post('/getindexclassify', function (req, res) {
  Classify.find({ "area": "index" }, (err, doc) => {
    // console.log(1);
    if (err) return console.error(err);
    if (doc.length === 0) {
      res.send({ status: 1 });
    } else {
      res.send({ status: 0, data: doc[0] });
    }
    res.end();
  });
});
// 获取二级页商品列表
router.post('/geterjiclassify', function (req, res) {
  Classify.find({ "area": "狗狗主粮" }, (err, doc) => {
    // console.log(1);
    if (err) return console.error(err);
    if (doc.length === 0) {
      res.send({ status: 1 });
    } else {
      res.send({ status: 0, data: doc[0] });
    }
    res.end();
  });
});
// 获取所有商品信息
router.get('/getproduct', function (req, res) {
  Product.find((err, doc) => {
    if (err) return console.error(err);
    if (doc.length === 0) {
      res.send({ status: 1 });
    } else {
      res.send({ status: 0, data: doc });
    }
    res.end();
  });
});

// 获取指定类别商品信息
router.get('/getareaproduct', function (req, res) {
  Product.find({ area: req.query.area }, (err, doc) => {
    if (err) return console.error(err);
    if (doc.length === 0) {
      res.send({ status: 1 });
    } else {
      res.send({ status: 0, data: doc });
    }
    res.end();
  });
});
// 获取指定id商品信息
router.get('/getidproduct', function (req, res) {
  Product.find({ _id: req.query._id }, (err, doc) => {
    if (err) return console.error(err);
    if (doc.length === 0) {
      res.send({ status: 1 });
    } else {
      res.send({ status: 0, data: doc });
    }
    res.end();
  });
});
// 添加商品信息
router.post('/insertproduct', function (req, res) {
  if (req.body.token !== "12345") {
    res.send({ status: 2 });
    res.end();
    return;
  }
  const product = new Product({
    "imgurl": req.body.imgurl,
    "title": req.body.title || null,
    "littleTitle": req.body.littleTitle || null,
    "price": req.body.price || null,
    "disPrice": req.body.disPrice || null,
    "area": req.body.area || null,
  });
  product.save((err, doc) => {
    if (err) return console.error(err);
    if (doc.ok !== 0) {
      res.send({ status: 0 });
    } else {
      res.send({ status: 1 });
    }
    res.end();
  });
});



module.exports = router;
